import { setToken, getToken } from '@/utils/auth'
import { login } from '@/api/login'

const userInfo = {
  state: {
    userId: '1',
    userName: 'admin',
    avatar: '',
    token: getToken(),
    auths: [],
    modules: [],
    role: 1, // 管理
  },
  getters: {},
  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_USERNAME: (state, name) => {
      state.userName = name
    },
    SET_USERID: (state, id) => {
      state.userId = id
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_AUTHS: (state, auths) => {
      state.auths = auths
    },
    SET_ROLE: (state, role) => {
      state.role = role
    },
  },
  actions: {
    Login({ commit }, params) {
      return new Promise<void>((resolve, reject) => {
        login(params).then(res => {
          if (res.code === 200) {
            const { token, userName, userId, avatar, auths, role } = res.result
            console.log(res.result)
            
            setToken(token)
            commit('SET_TOKEN', token)
            commit('SET_USERNAME', userName)
            commit('SET_USERID', userId)
            commit('SET_AVATAR', avatar)
            commit('SET_AUTHS', auths)
            commit('SET_ROLE', role)
            resolve()
          }
        }).catch(error => {
          reject(error)
        })
      })
    },
  },

}

export default userInfo